import React, { useEffect, useState } from "react";
import './apply.css';
import '../../Home/home.css'
import '../../../App.css'
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading, Toast } from "antd-mobile";
import { useDispatch } from "react-redux";
import { toPercentageString } from "@/utils/utils";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import icon_close from "@/assets/icon_close.png"
import icon_apply_increase1 from "@/assets/icon_apply_increase1.png"
import icon_apply_increase2 from "@/assets/icon_apply_increase2.png"
import icon_apply_increase3 from "@/assets/icon_apply_increase3.png"
import AddHomeEvent from "@/utils/addHomeEvent";
import { AmountRange } from "@/utils/amountRange";
import { setOrderInfo } from "@/utils/storage";
import { reqConfirmLoanApply, reqLoanDetailByAmount, reqSaveEvent, reqUserState } from "@/store/actions/apiServices";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";


export default function Apply() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //loading状态
    const [loanStategyVisible, setLoanStategyVisible] = useState(false)

    // 获取路由历史 history 对象
    const history = useHistory()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的proof信息
    const [loanDetailInfo, setLoanDetailInfo] = useState({})

    const onReqUserStateCallback = (success, resObj, pageTag) => {
        setMaskVisible(false);

        if (success && resObj) {
            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            if (isHomeSigning) {
                history.replace('/guide');
            } else if (isHomeReviewing) {
                history.replace('/review');
            } else if (isHomeReject) {
                history.replace('/reject');
            } else if (isHomeLoaning) {
                history.replace('/loaning');
            } else if (isHomeRepay) {
                history.replace('/repay');
            } else {
                if (resObj.isProofFinish) {
                    if (pageTag === PageTag.APPLY) {
                        if (resObj.userType === 'OLD') {
                            // 老客不用取默认值
                            checkLoanDetailInfoByAmount("");
                        } else {
                            // 新客取默认值
                            checkLoanDetailInfoByAmount(AmountRange.rank1);
                        }
                    }
                    if (pageTag === PageTag.APPLY_SUBMIT) {
                        doLoanApply();
                    }
                } else {
                    history.replace('/home');
                }
            }
        }
    };

    //确认申请
    const doLoanApply = () => {
        console.log("APPLY-confirmLoanApply: ");

        //确认申请
        try {
            //过滤days
            let days = loanDetailInfo.days;
            const daysList = loanDetailInfo.dayOptions.filter(item => {
                return item.selected;
            })
            if (daysList && daysList.length > 0) {
                days = daysList[0].label;
            }

            //过滤金额
            let amount = AmountRange.rank3;
            const amountList = loanDetailInfo.amountOptions.filter(item => {
                return item.selected;
            })
            if (amountList && amountList.length > 0) {
                amount = amountList[0].label;
            }

            setMaskVisible(true);
            reqConfirmLoanApply(amount, days, (success, resObj) => {
                setMaskVisible(false);
                if (success) {
                    // 保存订单号
                    const orderId = resObj.orderId || "";
                    setOrderInfo(orderId);
                    history.replace("/review");

                    // if (checkOSType() === "IOS") {
                    //     history.replace("/review")
                    // } else {
                    //     history.replace("/guide")
                    // }
                }
            });

        } catch (e) {
            console.log(e)
        }
    }

    //开始金额试算
    const checkLoanDetailInfoByAmount = (amount) => {
        console.log("checkLoanDetailInfoByAmount: ");
        try {
            setMaskVisible(true);
            reqLoanDetailByAmount(amount, loanDetailInfo, (success, resObj) => {
                setMaskVisible(false);
                if (success && resObj) {
                    setLoanDetailInfo(resObj);
                }
            });
        } catch (e) {
            console.log(e)
        }
    }

    //点击申请
    const onHandleApplyClick = () => {
        reqSaveEvent("APPLY_COMMIT_CLICK")

        //查询是否已选额度
        let hadAmountSelected = false
        for (let i = 0; i < loanDetailInfo.amountOptions.length; i++) {
            if (loanDetailInfo.amountOptions[i].selected === true) {
                hadAmountSelected = true
            }
        }
        if (!hadAmountSelected) {
            Toast.show("Please select amount first!")
            return
        }

        reqUserState(PageTag.APPLY_SUBMIT, onReqUserStateCallback);
    }

    //点击返回
    const onHandleNavGoBack = () => {
        history.replace("/home")
    }

    //点击金额返回
    const onHandleAmountClick = (amount, selected, index) => {
        if (!selected) {
            //更新状态
            const newState = { ...loanDetailInfo }
            for (let i = 0; i < newState.amountOptions.length; i++) {
                if (i === index) {
                    newState.amountOptions[i].selected = true
                } else {
                    newState.amountOptions[i].selected = false
                }
            }

            //更新状态
            setLoanDetailInfo(newState);

            //打点
            reqSaveEvent("APPLY_AMOUNT_CLICK", amount + "")

            if (loanDetailInfo.canSelectAmount === true) {
                //重新计算详情
                checkLoanDetailInfoByAmount(amount)
            } else {
                //显示弹框
                setLoanStategyVisible(true)
            }
        }
    }

    //点击日期返回
    const onHandleDayClick = (day, selected, index) => {
        if (!selected) {
            //显示弹框
            setLoanStategyVisible(true)

            //打点
            reqSaveEvent("APPLY_DAY_CLICK", day + "")
        }
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }

    //启动时请求首页额度
    useEffect(() => {
        //获取贷款详情
        try {
            //添加 fb 像素
            // eslint-disable-next-line no-undef
            // fbq('track', 'Page_Apply');
            // eslint-disable-next-line no-undef
            // gtag('track', 'Page_Apply');

            reqSaveEvent("APPLY_START");

            setMaskVisible(true);
            reqUserState(PageTag.APPLY, onReqUserStateCallback);

            return () => {
                reqSaveEvent("APPLY_END");
            }

        } catch (e) {
            console.log(e)
        }
    }, [])

    return (
        <div className="applyRoot">
            {/* 顶部背景 */}
            {/* <div className="applyTopBackground"></div> */}
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>Onua Credit</ProofNavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            {false && <div className="applyAmountContent">
                <div className="homeAmountTitle">Loan Amount</div>

                {/* 金额 */}
                <div className="contentRowCenter homeAmountAmountBottomAlign">
                    <div className="homeAmountCurrency">{loanDetailInfo.currency}</div>
                    <div className="homeAmountValue">{loanDetailInfo.amount}</div>
                </div>
            </div>}

            <div className="applyContent">
                {/* 选择金额 */}
                <div className="applyItemList contentVerticalPadding16Px">
                    <span className="applyItemBillHeaderTitle">Choose your loan amount</span>
                    <div className="applyItemSelectorContent">
                        {loanDetailInfo.isOldUser && loanDetailInfo.amountOptions && loanDetailInfo.amountOptions.map((value, index) => {
                            if (value.selected) {
                                return (
                                    <div className="applyItemSelectorSelected" key={index} onClick={() => { onHandleAmountClick(value.label, true, index) }}>{value.label}</div>
                                )
                            } else {
                                return (
                                    <div className="applyItemSelectorUnSelectBlank" key={index} onClick={() => { }}></div>
                                )
                            }
                        })}

                        {(!loanDetailInfo.isOldUser) && loanDetailInfo.amountOptions && loanDetailInfo.amountOptions.map((value, index) => {
                            if (value.selected) {
                                return (
                                    <div className="applyItemSelectorSelected" key={index} onClick={() => { onHandleAmountClick(value.label, true, index) }}>{value.label}</div>
                                )
                            } else {
                                return (
                                    <div className="applyItemSelectorUnSelect" key={index} onClick={() => { onHandleAmountClick(value.label, false, index) }}>{value.label}</div>
                                )
                            }
                        })}
                    </div>
                </div>

                {/* 选择日期 */}
                <div className="applyItemList contentVerticalPadding16Px">
                    <span className="applyItemBillHeaderTitle">Choose your loan term</span>
                    <div className="applyItemSelectorContent">
                        {loanDetailInfo.dayOptions && loanDetailInfo.dayOptions.map((value, index) => {
                            if (value.selected) {
                                return (
                                    <div className="applyItemSelectorSelected" key={index} onClick={() => { onHandleDayClick(value.label, true) }}>{value.label}</div>
                                )
                            } else {
                                return (
                                    <div className="applyItemSelectorUnSelect" key={index} onClick={() => { onHandleDayClick(value.label, false) }}>{value.label}</div>
                                )
                            }
                        })}
                    </div>
                </div>

                {/* 放款信息 */}
                <div className="applyItemList contentVerticalPadding">
                    <div className="applyItemBillContent">
                        <span className="applyItemBillHeaderTitle">Disburse amount</span>
                        <span className="applyItemBillHeaderAmount">{loanDetailInfo.realAmount}</span>
                        <span className="applyItemBillCurrency applyMainTextColor">{loanDetailInfo.currency}</span>
                    </div>
                    <div className="applyItemBillContent">
                        <span className="applyItemBillItemTitle">Loan amount</span>
                        <span className="applyItemBillItemAmount">{loanDetailInfo.amount}</span>
                        <span className="applyItemBillCurrency">{loanDetailInfo.currency}</span>
                    </div>
                    <div className="applyItemBillContent">
                        <span className="applyItemBillItemTitle">Service fee</span>
                        <span className="applyItemBillItemAmount">{loanDetailInfo.processingFee}</span>
                        <span className="applyItemBillCurrency">{loanDetailInfo.currency}</span>
                    </div>
                </div>

                {/* 还款信息 */}
                <div className="applyItemList">
                    <div className="applyItemBillContent">
                        <span className="applyItemBillHeaderTitle">Repayment amount</span>
                        <span className="applyItemBillHeaderAmount">{loanDetailInfo.repayAmount}</span>
                        <span className="applyItemBillCurrency applyMainTextColor">{loanDetailInfo.currency}</span>
                    </div>
                    <div className="applyItemBillContent">
                        <span className="applyItemBillItemTitle">Loan amount</span>
                        <span className="applyItemBillItemAmount">{loanDetailInfo.amount}</span>
                        <span className="applyItemBillCurrency">{loanDetailInfo.currency}</span>
                    </div>
                    <div className="applyItemBillContent">
                        <span className="applyItemBillItemTitle">Interest</span>
                        <span className="applyItemBillItemAmount">{loanDetailInfo.interest}</span>
                        <span className="applyItemBillCurrency">{loanDetailInfo.currency}</span>
                    </div>
                    <div className="applyItemBillContent">
                        <span className="applyItemBillItemTitle">Service fee</span>
                        <span className="applyItemBillItemAmount">{loanDetailInfo.repayProFee}</span>
                        <span className="applyItemBillCurrency">{loanDetailInfo.currency}</span>
                    </div>
                    <div className="applyItemBillContent">
                        <span className="applyItemBillItemTitle">Overdue penalty interest</span>
                        <span className="applyItemBillItemAmount">{toPercentageString(loanDetailInfo.overdueRate)} per day</span>
                        <span className="applyItemBillCurrency"></span>
                    </div>
                </div>

                <div className="applyOverlayIconIncrease"></div>
                <div className="applyOverlayIconIncrease"></div>
            </div>

            {/* 首页点击申请 */}
            <div className="applyApplyBtn" onClick={onHandleApplyClick}>
                <div className="mainButtonGradient">Apply Now</div>
            </div>

            {/* load mask https://mobile.ant.design/zh/components/mask/ */}
            <Mask visible={loanStategyVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="applyOverlayBg">
                    <div className="applyOverlayContent">
                        <div className="applyOverlayContentIconClose" onClick={() => { setLoanStategyVisible(false) }}>
                            <img className="applyOverlayIconClose" src={icon_close} alt="" />
                        </div>
                        <div className="applyOverlayContentHeaderTitle">Loan strategy</div>
                        <div className="applyOverlayContentRowTitle">Quickly increase the personal loan amount and term all you need to do</div>
                        <div className="applyOverlayContentRowTitle">Strategy 1: Pay off each loan in full and on time.</div>
                        <div className="applyOverlayContentRowTitle">Strategy 2: Continuous use, the more borrowing times, the higher the amount, and the lower the fee.</div>
                        <div className="applyOverlayContentIconIncrease">
                            <img className="applyOverlayIconIncrease" src={icon_apply_increase1} alt="" />
                            <div className="applyOverlayIconIncreaseSpace"></div>
                            <img className="applyOverlayIconIncrease" src={icon_apply_increase2} alt="" />
                        </div>
                        <div className="applyOverlayContentIconIncrease">
                            <img className="applyOverlayIconIncreaseLarge" src={icon_apply_increase3} alt="" />
                        </div>
                    </div>
                </div>
            </Mask>

            {/* add home gif dialog */}
            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}